package com.example.day8_sp;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity2 extends AppCompatActivity {

    private EditText username;
    private EditText password;
    private CheckBox cb;
    SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        initView();
        sp = getSharedPreferences("login",MODE_PRIVATE);
        //打开时，判断上次进入APP时，是否进行了记住密码的操作，进行了--展示用户名和密码   未进行，不做任何操作
        boolean checked = sp.getBoolean("isChecked", false);
        if(checked){//上次选中显示用户名和密码
            username.setText(sp.getString("name",""));
            password.setText(sp.getString("pwd",""));
            cb.setChecked(sp.getBoolean("isChecked",false));
        }
    }

    public void login(View view) {
        //点击登录时，判断复选框是否选中，如果选中，将用户名和密码保存  未，不做任何操作
        if(cb.isChecked()){
            sp.edit().putString("name",username.getText().toString())
                    .putString("pwd",password.getText().toString())
                    .putBoolean("isChecked",true)
                    .commit();
        }else{
            sp.edit().putBoolean("isChecked",false).commit();
        }
        startActivity(new Intent(this,MainActivity.class));
    }

    private void initView() {
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        cb = (CheckBox) findViewById(R.id.cb);
    }
}